package com.le.tester.soundCode;

import org.apache.tomcat.util.http.fileupload.InvalidFileNameException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 描述：文件名的检查
 */
public class FileNameChecker {

    private static final Logger LOG = LoggerFactory.getLogger(FileNameChecker.class);

    private final char[] value = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

    private static String checkFileName(String fileName) {
        if (fileName != null && fileName.indexOf(0) != -1) {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < fileName.length(); ++i) {
                char c = fileName.charAt(i);
                switch (c) {
                    case '\u0000':
                        sb.append("\\0");
                        break;
                    default:
                        sb.append(c);
                }
            }

            throw new InvalidFileNameException(fileName, "Invalid file name: " + sb);
        } else {
            return fileName;
        }
    }

    private int indexOf(int ch, int fromIndex) {
        final int max = value.length;
        if (fromIndex < 0) {
            fromIndex = 0;
        } else if (fromIndex >= max) {
            // Note: fromIndex might be near -1>>>1.
            return -1;
        }

        if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
            // handle most cases here (ch is a BMP code point or a
            // negative value (invalid code point))
            final char[] value = this.value;
            for (int i = fromIndex; i < max; i++) {
                LOG.info("this value is {}", value[i]);
                LOG.info("target value is {}", ch);
                if (value[i] == ch) {
                    return i;
                }
            }
            return -1;
        } else {
            return indexOfSupplementary(ch, fromIndex);
        }
    }

    private int indexOfSupplementary(int ch, int fromIndex) {
        if (Character.isValidCodePoint(ch)) {
            final char[] value = this.value;
            final char hi = Character.highSurrogate(ch);
            final char lo = Character.lowSurrogate(ch);
            final int max = value.length - 1;
            for (int i = fromIndex; i < max; i++) {
                if (value[i] == hi && value[i + 1] == lo) {
                    return i;
                }
            }
        }
        return -1;
    }

    public static void main(String[] args) {
//        FileNameChecker fileNameChecker = new FileNameChecker();
//        int i = fileNameChecker.indexOf(0, 0);
//        LOG.info("返回的索引:{}", i);
        LOG.info("开始检查文件");
        String fileName = FileNameChecker.checkFileName("http://imgs.firestudyonline.cn/firefly/1607087076250_1607087076250.png?time=1607087076250");
        int i = fileName.indexOf(0);
        LOG.info("文件名：{}", fileName);
    }
}
